(function () {
  function isArray(ary){
    return Object.prototype.toString.call(ary) === "[object Array]";
  }

  function isAtomic(ary){
    return ary.filter(function(item){
      return isArray(item);
    })
  }

  function mapary(ary){
    var res = []
    while(ary.length > 0){
      var item = ary.shift();
      if (!isArray(item)) {
        res.push(item)
      } else if(isAtomic(item)){
        res.push(JSON.stringify(item))
      } else {
        for (var i = 0; i <= item.length-1; i++){
          ary.unshift(item[i]);
        }
      }
    }
    return res.join();
  }

  function post(error) {
      var req = new XMLHttpRequest();
      if (req.overrideMimeType) req.overrideMimeType("text/xml");
      if (req) {
          req.open("POST", "/wechat/watcher/", true);
          req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
          req.onreadystatechange = function () {
              if (req.readyState == 4 && req.status == 200) {
              }
          }
          req.send("error=" + error);
      }
  }

  function stringify(dom) {
      var arg = null,
          oType = Object.prototype.toString.call(dom);
      switch (oType) {
          case oType === "[object Array]":
              arg = mapary(dom);
              break;
          case oType === "[object Error]":
          case oType === "[object Object]" && dom.toString:
              arg = dom.toString();
              break;
          default:
              arg = dom;
      }
      try {
          arg = JSON.stringify(arg);
      } catch (e) {
      }
      return arg;
  }

  console.error = function () {
      if(arguments.length===0) return;
      var arg = [];
      for (var i in arguments) {
          arg.push(stringify(arguments[i]))
      }
      post(arg.join());
  }

  window.onerror = function (message, url, line, column, obj) {
      var o = {};
      o.error = stringify(message);
      o.url = url;
      o.line = line;
      o.column = column;
      o.object = obj;

      post(JSON.stringify(o));
  }
})()
